package com.example.myapplication.module_common_service;

import static com.example.myapplication.utils.UserService.JSON;

import android.annotation.SuppressLint;
import android.os.Build;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.fragment.app.Fragment;

import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.example.myapplication.R;
import com.example.myapplication.data.GlobalData;
import com.example.myapplication.data.MySchedule;
import com.google.firebase.crashlytics.buildtools.reloc.com.google.common.reflect.TypeToken;
import com.google.gson.Gson;
import com.zhuangfei.timetable.TimetableView;
import com.zhuangfei.timetable.listener.ISchedule;
import com.zhuangfei.timetable.listener.IWeekView;
import com.zhuangfei.timetable.model.Schedule;
import com.zhuangfei.timetable.view.WeekView;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import okhttp3.Call;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;


@SuppressLint("HandlerLeak")
public class CoursesFragment extends Fragment {
    private static final int GET_DATA = 1;
    private static final int DEL_DATA = 2;
    private static final int ADD_COURSE = 3;
    LinearLayout root;
    WeekView weekView;
    TimetableView timetableView ;
    List<MySchedule> data = new ArrayList<>();
    public CoursesFragment() {
        // Required empty public constructor
    }    Handler handler = new Handler(){
        @Override
        public void handleMessage(@NonNull Message msg) {
            switch (msg.what){
                case GET_DATA:
                    Object obj = msg.obj;
                    if(obj==null){
                        return;
                    }
                    timetableView.source((List<MySchedule>) obj);
                    timetableView.updateView();

                    weekView.source((List<MySchedule>) obj)
                            .curWeek(1)
                            .callback(new IWeekView.OnWeekItemClickedListener() {
                                @Override
                                public void onWeekClicked(int week) {
                                    int cur = timetableView.curWeek();
                                    //更新切换后的日期，从当前周cur->切换的周week
                                    timetableView.onDateBuildListener()
                                            .onUpdateDate(cur, week);
                                    //课表切换周次
                                    timetableView.changeWeekOnly(week);
                                }
                            })
                            .callback(new IWeekView.OnWeekLeftClickedListener() {
                                @Override
                                public void onWeekLeftClicked() {

                                }
                            }).hideLeftLayout().
                            isShow(true
                            )//设置隐藏，默认显示
                            .showView();
                    break;
                case DEL_DATA:
                    //删除数据后重新获取

                    Toast.makeText(getContext(),"删除成功！！",Toast.LENGTH_LONG).show();
                    getData();
                    break;
                case ADD_COURSE:
                    Toast.makeText(getContext(),"加课成功！！",Toast.LENGTH_LONG).show();
                    getData();
                    break;
            }
        }
    };

    public static CoursesFragment newInstance(String param1, String param2) {
        CoursesFragment fragment = new CoursesFragment();
        Bundle args = new Bundle();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    @Override
    public void onStart() {
        super.onStart();
        if(GlobalData.isLogin){
            getData();
        }
    }

    private void getData(){
        OkHttpClient okHttpClient = new OkHttpClient();

        String substring = GlobalData.jwt.substring(1, GlobalData.jwt.length() - 1);
        Request request = new Request.Builder().
                url("http://120.25.230.35:8080/schedule").addHeader("jwt", substring).get().build();
        Call call = okHttpClient.newCall(request);
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Response execute = call.execute();
                    if(execute.isSuccessful()){
                        Message message = new Message();
                        //把jwt传进去
                        String string = execute.body().string();
                        Log.d("fuck", "run: "+string);
                        Gson gson = new Gson();
                        List<MySchedule> data2 = gson.fromJson(string, new TypeToken<List<MySchedule>>() {
                        }.getType());
                        message.obj = data2;
                        message.what = GET_DATA;
                        handler.sendMessage(message);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    private void delCourse(String cName){
        OkHttpClient okHttpClient = new OkHttpClient();

        String substring = GlobalData.jwt.substring(1, GlobalData.jwt.length() - 1);
        Request request = new Request.Builder().
                url("http://120.25.230.35:8080/schedule?name="+cName).addHeader("jwt", substring).delete().build();
        Call call = okHttpClient.newCall(request);
        try {
            Response execute = call.execute();
            if(execute.isSuccessful()){
                Message message = new Message();
                //把jwt传进去
                String string = execute.body().string();
                message.what = DEL_DATA;
                handler.sendMessage(message);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        // Inflate the layout for this fragment
        root = (LinearLayout) inflater.inflate(R.layout.fragment_courses, container, false);
        initTimeTableView();
        if(GlobalData.isLogin){
            getData();
        }

        return root;
    }

    private void initTimeTableView(){
        timetableView = root.findViewById(R.id.id_timetableView);
        weekView = root.findViewById(R.id.weekview);
        timetableView.source(data);
        timetableView.curWeek("2022-09-01 00:00:00");
        timetableView.isShowFlaglayout(true);
        timetableView.showDateView();
        timetableView.callback(new ISchedule.OnItemClickListener(){
            @Override
            public void onItemClick(View v, List<Schedule> scheduleList) {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                    scheduleList.forEach(schedule -> {

                        View infoCourse = getLayoutInflater().inflate(R.layout.info_course,null);
                        TextView teacher = infoCourse.findViewById(R.id.tv_teacher);
                        teacher.setText(schedule.getTeacher());
                        TextView cName = infoCourse.findViewById(R.id.tv_course_name);
                        cName.setText(schedule.getName());
                        TextView room = infoCourse.findViewById(R.id.tv_room);
                        room.setText(schedule.getRoom());

                        TextView weeks = infoCourse.findViewById(R.id.tv_weeks);
                        weeks.setText(schedule.getWeekList().toString());

                        infoCourse.findViewById(R.id.btn_del_course).setOnClickListener(
                                new View.OnClickListener() {
                                    @Override
                                    public void onClick(View view) {
                                        new Thread(new Runnable() {
                                            @Override
                                            public void run() {
                                                delCourse(cName.getText().toString());
                                            }
                                        }).start();
                                    }
                                }
                        );

                        new AlertDialog.Builder(getContext()).setView(infoCourse).show();
                    });
                }

            }
        });
        timetableView.callback(new ISchedule.OnSpaceItemClickListener() {
            @Override
            public void onSpaceItemClick(int day, int start) {
                if (day==0){
                    return;
                }
                View addCourse = getLayoutInflater().inflate(R.layout.add_course,null);

                addCourse.findViewById(R.id.btn_cfm_add_course).setOnClickListener(view -> {
                    MySchedule mySchedule = new MySchedule();
                    EditText cName = addCourse.findViewById(R.id.new_cName);
                    mySchedule.setName(cName.getText().toString());
                    EditText tName = addCourse.findViewById(R.id.new_tName);
                    mySchedule.setTeacher(tName.getText().toString());
                    EditText room = addCourse.findViewById(R.id.new_room);
                    mySchedule.setRoom(room.getText().toString());
                    EditText step = addCourse.findViewById(R.id.new_cStep);
                    mySchedule.setStep(Integer.parseInt(step.getText().toString()));
                    EditText weeks = addCourse.findViewById(R.id.new_Weeks);
                    String[] split = weeks.getText().toString().split(",");
                    List<Integer> ints = new ArrayList<>();
                    for (String s:
                        split ) {
                        int i = Integer.parseInt(s);
                        ints.add(i);
                    }

                    mySchedule.setDay(day);
                    mySchedule.setStart(start);
                    mySchedule.setWeekList(ints);
                    doAddCourse(mySchedule);

                });

                new AlertDialog.Builder(getContext()).setView(addCourse).show();
            }

            @Override
            public void onInit(LinearLayout flagLayout, int monthWidth, int itemWidth, int itemHeight, int marTop, int marLeft) {

            }
        });
        timetableView.showView();
    }
    private void doAddCourse(MySchedule mySchedule){
        new Thread(new Runnable() {
            @Override
            public void run() {
                OkHttpClient okHttpClient = new OkHttpClient();

                String substring = GlobalData.jwt.substring(1, GlobalData.jwt.length() - 1);
                Gson gson = new Gson();

                RequestBody requestBody = RequestBody.create(JSON,gson.toJson(mySchedule));
                Request request = new Request.Builder().
                        url("http://120.25.230.35:8080/schedule").addHeader("jwt", substring).post(requestBody).build();
                Call call = okHttpClient.newCall(request);
                try {
                    Response execute = call.execute();
                    if(execute.isSuccessful()){
                        Message message = new Message();
                        //把jwt传进去
                        String string = execute.body().string();
                        message.what = ADD_COURSE;
                        handler.sendMessage(message);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }



}